package com.ly.config;

import cn.hutool.core.util.StrUtil;
import com.ly.common.StatusEnum;
import com.ly.dao.UserTokenDao;
import com.ly.entity.UserToken;
import com.ly.exp.ServiceException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class Md5TokenInterceptor implements HandlerInterceptor {
    @Resource
    private UserTokenDao userTokenDao;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从请求头获取token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            throw new ServiceException(StatusEnum.UNAUTHORIZED.getCode(),"token过期重新登录");
        }
        //2. 查询数据库进行比对
        UserToken userToken = userTokenDao.selectByToken(token);
        if(Objects.isNull(token)){
            throw new ServiceException(StatusEnum.UNAUTHORIZED.getCode(),"token过期重新登录");
        }
        return true;
    }
}
